package com.smartcruise.main.mainFragment.tools;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.smartcruise.R;
import com.smartcruise.base.BaseFragment;
import com.smartcruise.util.BarUtils;
import com.smartcruise.util.customView.ChaosCompassView;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.content.Context.SENSOR_SERVICE;

/**
 * Created by FengChaoQun
 * on 2018/1/21 0021
 * 指南针
 */

public class CompassFragment extends BaseFragment implements AMapLocationListener {

    @BindView(R.id.compass)
    ChaosCompassView compass;
    Unbinder unbinder;
    @BindView(R.id.locationDetail)
    TextView locationDetail;

    private SensorManager mSensorManager;
    private SensorEventListener mSensorEventListener;
    private float val;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getRootView(R.layout.fragment_compass);
        unbinder = ButterKnife.bind(this, rootView);
        init();
        return rootView;
    }

    private void init() {

        mSensorManager = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE);

        BarUtils.setColor(getActivity(), getResources().getColor(R.color.b0), 0);

        mSensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                val = event.values[0];
                compass.setVal(val);
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        };

        mSensorManager.registerListener(mSensorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);

        mlocationClient = new AMapLocationClient(getActivity());
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        mLocationOption.setSensorEnable(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        mSensorManager.unregisterListener(mSensorEventListener);
        mlocationClient.onDestroy();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(amapLocation.getProvince()).append("  ").append(amapLocation.getCity())
                        .append("\n")
                        .append("北纬").append(decimalFormat.format(amapLocation.getLatitude())).append("  ")
                        .append("东经").append(decimalFormat.format(amapLocation.getLongitude()))
                        .append("\n")
                        .append("海拔").append("  ").append(amapLocation.getAltitude()).append("米");
                locationDetail.setText(stringBuilder);
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

}
